package com.xl6667.filter;

import com.xl6667.enums.AppHttpCodeEnum;
import com.xl6667.exception.SystemException;
import com.xl6667.service.impl.SmsDetailsServiceImpl;
import com.xl6667.util.RedisCache;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 短信登陆鉴权 Provider，要求实现 AuthenticationProvider 接口
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {
    private SmsDetailsServiceImpl smsDetailsService;

    private RedisCache redisCache;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;

        String phoneNumber = (String) authenticationToken.getPrincipal();

        checkSmsCode(phoneNumber);

        UserDetails userDetails = smsDetailsService.loadUserByUsername(phoneNumber);

        // 此时鉴权成功后，应当重新 new 一个拥有鉴权的 authenticationResult 返回
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userDetails, userDetails.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    private void checkSmsCode(String mobile) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String inputCode = request.getParameter("code");
        String smsCode = redisCache.getCacheObject("smscode:"+mobile).toString();
        if(smsCode == null) {
            throw new SystemException(AppHttpCodeEnum.LOGIN_SMS_REDIS);
        }
        if(!smsCode.equals(inputCode)) {
            throw new SystemException(AppHttpCodeEnum.NO_CODE);
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // 判断 authentication 是不是 SmsCodeAuthenticationToken 的子类或子接口
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService() {
        return smsDetailsService;
    }

    public void setUserDetailsService(SmsDetailsServiceImpl smsDetailsService) {
        this.smsDetailsService = smsDetailsService;
    }

    public void setRedisCache(RedisCache redisCache) {
        this.redisCache = redisCache;
    }
}
